import React from "react";
import { Upload, Icon, message, Modal } from "antd";
import { UploadFile } from "antd/lib/upload/interface";
import { IResponseData, IResponseError } from "../services/CommonTypes";

interface IImgUploaderProps {
  curImgUrl?: string;
  onChange?: (imgUrl: string) => void;
}

interface IImgState {
  showModal: boolean;
}

export default class extends React.Component<IImgUploaderProps,IImgState> {
  state: IImgState = {
    showModal: false
  };

  private getUploadContent() {
    if (this.props.curImgUrl) {
      return null;
    } else {
      return (
        <div>
          <Icon type="plus" />
          <div>点击上传</div>
        </div>
      );
    }
  }

  private getFileList(): UploadFile[] {
    if (this.props.curImgUrl) {
      return [
        {
          uid: this.props.curImgUrl,
          name: this.props.curImgUrl,
          url: this.props.curImgUrl
        }
      ];
    }
    return [];
  }

  async handleRequest(p: any) {
    console.log(p);
    let formData = new FormData();
    formData.append(p.filename, p.file);
    // fetch api
    const request = new Request(p.action, {
      method: "post",
      body: formData
    });
    const resp: IResponseData<string> | IResponseError = await fetch(
      request
    ).then(resp => resp.json());

    if (resp.err) {
      // 有错误
      message.error("上传失败!");
    } else {
      // 触发回调
      if(this.props.onChange){
        this.props.onChange(resp.data!);
      }
    }
    console.log(resp);
  }

  render() {
    return (
      <div>
        <Upload
          action="/api/upload"
          name="imgfile"
          accept=".jpg,.png,.gif"
          listType="picture-card"
          fileList={this.getFileList()}
          customRequest={this.handleRequest.bind(this)}
          onRemove={() => {
            if(this.props.onChange){
              this.props.onChange("");
            }
          }}
          onPreview={() => {
            this.setState({
              showModal:true
            })
          }}
        >
          {this.getUploadContent()}
        </Upload>
        <Modal
          visible={this.state.showModal}
          footer={null}
          onCancel={() => {
            this.setState({
              showModal: false
            });
          }}
        >
          <img
            src={this.props.curImgUrl}
            alt="example"
            style={{ width: "100%" }}
          />
        </Modal>
      </div>
    );
  }
}
